var app = getApp();
var commonURLYY = app.data.newURL;
var GZHid=53;//公众号id
Page({
  data:{
    carts: [],
    hasblock: false,
    hasList: false,  //列表是否有数据
    totalPrice: 0,   //总价初始数为0
    // selectallStatus: true, //商品选中状态
    del_dialog: false   //删除商品弹窗
  },
  onLoad:function(){
    var that = this;   
    var openId = app.data.openid || wx.getStorageSync('openid')
    wx.getStorage({
      key: 'xiaoqu',
      success: function(res) {
        that.setData({
          areaid:res.data.item.id
        })
      },
    })
  },
  delateGoods: function (cid){
    var that=this;
    wx.request({
      url: commonURLYY + 'op=cart_del',
      data: {
        id: cid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.request({
          url: commonURLYY + 'op=cart_view&ii=' + app.data.openid,
          data: {
            openid: app.data.openid,
            areaid: that.data.areaid
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            var lists = res.data.list;
            var num = 0;
            for (var i = 0; i < lists.length; i++) {
              num = num + lists[i].num;
            }
            console.log(num, ':num')
            wx.setTabBarBadge({
              index: 1,
              text: '' + num
            })
            that.setData({
              carts: lists
            })
          }
        })
      }
    })
  },
  onShow: function (option) {
    var that = this;
    wx.getStorage({
      key: 'xiaoqu',
      success: function (res) {
    console.log(that.data.areaid, 418416416416)
    var openId = app.data.openid || wx.getStorageSync('openid')  
    wx.request({
      url: commonURLYY+ 'op=cart_view',
      data: {
        openid: openId,
        areaid: res.data.item.id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var _that=that;
        var lists = res.data.list;
        console.log(lists)
        for (var i = 0; i < lists.length;i++){
          if (lists[i].kucun == 0 || lists[i].isshow == '3') {
            var pay = lists[i].title + '已售罄，请先删除该产品再去支付';
            var cid = lists[i].id
            wx.showToast({
              title: '' + pay,
              icon: 'none',
              duration: 4000
            })
            _that.delateGoods(cid)
          }
          if (lists[i].spike == 1 && lists[i].spike_end <= Date.parse(new Date()) / 1000) {
            var pay = lists[i].title + '活动已结束，请先删除该产品再去支付';
            var cid = lists[i].id
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: pay,
              success(res) {
                if (res.confirm) {
                  _that.delateGoods(cid)
                }
              }
            })
          }
          if (lists[i].is_on == 0) {
            var pay = lists[i].title + '已下架，请先删除该产品再去支付';
            var cid = lists[i].id
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: pay,
              success(res) {
                if (res.confirm) {
                  _that.delateGoods(cid)
                }
              }
            })
          }
          if (lists[i].isshow == 2) {
            var pay = lists[i].title + '已下架，请先删除该产品再去支付1';
            var cid = lists[i].id
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: pay,
              success(res) {
                if (res.confirm) {
                  _that.delateGoods(cid)
                }
              }
            })
          }
          if (lists[i].is_applet == 0) {
            var pay = lists[i].title + '已下架，请先删除该产品再去支付';
            var cid = lists[i].id
            wx.showModal({
              title: '提示',
              showCancel:false,
              content: pay,
              success(res) {
                if (res.confirm) {
                  _that.delateGoods(cid)
                } 
              }
            })          
          }
        }
        var num = 0;
        for (var i = 0; i < lists.length; i++) {
          num = num + lists[i].num;
        }
        console.log(num, ':num')
        wx.setTabBarBadge({
          index: 1,
          text: '' + num
        })
        that.setData({
          carts: res.data.list
        })
        that.getTotalPrice();
        if(res.data.list.length){
        that.setData({
            hasList: true
          })
        }
      }
    })
      }
    })
  },
  onHide: function () { //页面每次隐藏的时候调用接口,记录用户操作

  }, 
  getTotalPrice: function () {  //页面上所有涉及到商品的操作都要引用这个函数
    var carts = this.data.carts;
    var total = 0; 
    carts.forEach(function (item) {  //累加所有选中的商品
      if(item.discount){
        total += item.num * item.oprice;
      }else{
        total += item.num * item.price;
      }
    });
    this.setData({
      carts: carts,
      totalPrice: total.toFixed(2) 
    })
  },
  selectList: function (e) {  
    var index = e.currentTarget.dataset.index;
    var carts = this.data.carts;
    var selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({
      carts: carts
    });
    this.getTotalPrice(); 
  },
  selectAll: function () {
    var selectallStatus = this.data.selectallStatus;
    selectallStatus = !selectallStatus;
    var carts = this.data.carts;
    carts.forEach(function (item) { 
      item.selected = selectallStatus;
    })
    this.setData({
      selectallStatus: selectallStatus,
      carts:carts
    })
    this.getTotalPrice();
  },
  addCount: function (e) {
    var index = e.currentTarget.dataset.index;
    var carts = this.data.carts;
    var num = Number(carts[index].num);
    var id = carts[index].id;
    var sid = carts[index].sid;
    var that=this;
    that.setData({
      hasblock: true,
    })
    var pay='';
    //判断虚拟库存
    if (this.data.carts[index].cnum<=0){
      wx.showToast({
        title: '该商品库存已被抢占，请稍后再试',
        icon: 'none',
        duration: 4000
      })
      that.setData({
        hasblock: false
      })
      return;
    }
    //判断库存
    if (this.data.carts[index].kucun == 0 || this.data.carts[index].isshow == '3') {
      pay = this.data.carts[index].title + '已售罄，请先删除该产品';
      wx.showToast({
        title: '' + pay,
        icon: 'none',
        duration: 4000
      })
      that.setData({
        hasblock: false
      })
      return;
    }
    if (this.data.carts[index].isshow == 2) {
      pay = this.data.carts[index].title + '已下架，请先删除该产品',
      wx.showToast({
        title: '' + pay,
        icon: 'none',
        duration: 4000
      })
      that.setData({
        hasblock: false
      })
      return;
    }
    num = num + 1;
    if (this.data.carts[index].onelimit == 0) {
      if (num > 1) {
        pay = this.data.carts[index].title + '该商品单次购买数量限制1件';
        wx.showToast({
          title: '' + pay,
          icon: 'none',
          duration: 4000
        })
        that.setData({
          hasblock: false
        })
        return;
      }
    } else {
      if (num > this.data.carts[index].onelimit) {
        pay = this.data.carts[index].title + '该商品单次购买数量限制' + this.data.carts[index].onelimit + '件';
        wx.showToast({
          title: '' + pay,
          icon: 'none',
          duration: 4000
        })
        that.setData({
          hasblock: false
        })
        return;
      }
    }
    if (this.data.carts[index].manylimit == 0) {
      if (999999 <= this.data.carts[index].history_limit + this.data.carts[index].num) {
        pay = this.data.carts[index].title + '该商品已达到总限购数量' + this.data.carts[index].manylimit;
        wx.showToast({
          title: '' + pay,
          icon: 'none',
          duration: 4000
        })
        that.setData({
          hasblock: false
        })
        return
      }
    } else {
      if (this.data.carts[index].manylimit <= this.data.carts[index].history_limit + this.data.carts[index].num) {
        pay = this.data.carts[index].title + '已达到总限购数量' + this.data.carts[index].manylimit;
        wx.showToast({
          title: '' + pay,
          icon: 'none',
          duration: 4000
        })
        that.setData({
          hasblock: false
        })
        return
      }
    } 
    
    carts[index].num = num;
      that.setData({
        carts: carts
      })
      that.getTotalPrice();
      that.changeNum(id, sid, num, index);
    wx.request({
      url: commonURLYY + 'op=cart_view&ii=' + app.data.openid,
      data: {
        openid: app.data.openid,
        areaid: that.data.areaid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var lists = res.data.list;
        var num = 0;
        for (var i = 0; i < lists.length; i++) {
          num = num + lists[i].num;
        }
        wx.setTabBarBadge({
          index: 1,
          text: '' + num
        })
      }
    })
  },
  reduceCount: function (e) {
    var that=this;
    var index = e.currentTarget.dataset.index;
    var carts = this.data.carts;
    var num = Number(carts[index].num);
    var id = carts[index].id;
    var sid = carts[index].sid;
    if(num <= 1 ){
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    })
    this.getTotalPrice();
    this.changeNum(id,sid,num,index)
    wx.request({
      url: commonURLYY + 'op=cart_view&ii=' + app.data.openid,
      data: {
        openid: app.data.openid,
        areaid: that.data.areaid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var lists = res.data.list;
        var num = 0;
        for (var i = 0; i < lists.length; i++) {
          num = num + lists[i].num;
        }
        wx.setTabBarBadge({
          index: 1,
          text: '' + num
        })
      }
    })
  },
  deleteList: function (e) {
    var that = this;
    var _index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '删除',
      content: '是否删除该商品？',
      showCancel: true,//是否显示取消按钮
      cancelText: "取消",//默认是“取消”
      cancelColor: '#333',//取消文字的颜色
      confirmText: "确定",//默认是“确定”
      confirmColor: '#3cc51f',//确定文字的颜色
      success: function (res) {
        if (res.cancel){
          //点击取消,默认隐藏弹框
        }else{
            var carts = that.data.carts;
            var cid = that.data.carts[_index].id;
            carts.splice(_index, 1);
            that.setData({
              carts: carts
            })
            if (!carts.length) {
              that.setData({
                hasList: false
              })
            } else {
              that.getTotalPrice();
            }
            wx.request({
              url: commonURLYY + 'op=cart_del',
              data: {
                id: cid
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                wx.request({
                  url: commonURLYY + 'op=cart_view&ii=' + app.data.openid,
                  data: {
                    openid: app.data.openid,
                    areaid: that.data.areaid   
                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                    var lists = res.data.list;
                    var num = 0;
                    for (var i = 0; i < lists.length; i++) {
                      num = num + lists[i].num;
                    }
                    console.log(num, ':num')
                    wx.setTabBarBadge({
                      index: 1,
                      text: '' + num
                    })
                  }
                })
              }
            })
        }  
      }
    })
  },
  go_pay: function (e) {  //去支付
    var formid = e.detail.formId;
    var pay='去支付';
    var that=this;
    for (var i=0;this.data.carts.length>i;i++){
      if (this.data.carts[i].kucun == 0 || this.data.carts[i].isshow == '3'){
        pay = this.data.carts[i].title +'已售罄，请先删除该产品'
      }
      if (this.data.carts[i].cnum < 0){
        pay = this.data.carts[i].title + '库存已被抢完'
      }
      if (this.data.carts[i].spike == 1 && this.data.carts[i].spike_end <= Date.parse(new Date()) / 1000){
        pay = this.data.carts[i].title+'活动已结束，请先删除该产品'
      }
      if (this.data.carts[i].is_on == 0 ) {
        pay = this.data.carts[i].title + '已下架，请先删除该产品'
      }
      if (this.data.carts[i].isshow == 2) {
        pay = this.data.carts[i].title + '已下架，请先删除该产品'
      }
      if (this.data.carts[i].is_applet == 0) {
        pay = this.data.carts[i].title + '已下架，请先删除该产品'
      }
      //限制单次购买数量
      if (this.data.carts[i].onelimit == 0) {
        if (this.data.carts[i].num > 1) {
          pay = this.data.carts[i].title + '单次购买数量限制1件'
        }
      } else {
        if (this.data.carts[i].num > this.data.carts[i].onelimit) {
          pay = this.data.carts[i].title + '该商品单次购买数量限制' + this.data.carts[i].onelimit + '件'
        }
      }
      //限制总限制数量
      if (this.data.carts[i].manylimit == 0) {
        if (99999 <= this.data.carts[i].history_limit + this.data.carts[i].num) {
          pay = this.data.carts[i].title + '已达到总限购数量' + this.data.carts[i].manylimit
        }
      } else {
        if (this.data.carts[i].manylimit < this.data.carts[i].history_limit + this.data.carts[i].num) {
          pay = this.data.carts[i].title + '已达到总限购数量' + this.data.carts[i].manylimit
        }
      }
    }
    wx.request({
      url: commonURLYY + 'op=goPay',
      data: {
        openid: app.data.openid,
        uniacid: app.data.GZHid
      },
      success: function (res) {
        if(res.data.status==0){
          wx.showToast({
            title: '购物车商品已超库存，系统将自动调整',
            icon: 'none',
            duration: 2500
          })
          that.onShow();
        } else if (res.data.status == 2){
          wx.showToast({
            title: '购物车存放时间过长，系统将自动清除',
            icon: 'none',
            duration: 2500
          })
          that.onShow();
        }else{
          if (pay == '去支付') {
            var length = that.data.carts.length
            if (length) {
              wx.navigateTo({
                url: '../index_cart/index_cart'
              })
            }
          } else {
            wx.showToast({
              title: '' + pay,
              icon: 'none',
              duration: 4000
            })
          } 
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  changeNum: function (id, gid, num,index) {
    var that=this;
    wx.request({
      url: commonURLYY + 'op=cart_edit',
      data: {
        id: id,
        gid: gid,
        num: num
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // console.log(res)
        var cnum1 ="carts["+index+"].cnum"
        console.log(res.data.cnum,cnum1)
        wx.showToast({
          title: '修改成功',
        })
        that.setData({
          hasblock:false,
          [cnum1]: res.data.cnum
        })
      }
    })
  }
})